const app = getApp();
var utils = require("../../utils/utils.js");
var server = require("../../utils/server.js");
var config = require("../../config.js");
var apis = require("../../utils/api.js");

Page({
  data: {
    dataList: [],
    checkIndex: -1,
    zdy: false,
    loading: false,
    nodata: true,
    showFilter: false,
    isChange: false,
    pageNo: 1,
    pageSize: 10,
    isLast: false,
    authStatus: app.globalData.userInfo.authStatus,
    showSearchIcon: true,
    keyword: '',
    options: [],
    port: '',
    selectedIndex: '',
    status: '2',
    bgColor: '#ffffff', // 初始颜色为白色
    statusArray: [{
        status: '1',
        name: '已完成'
      },
      {
        status: '2',
        name: '未完成'
      },
      {
        status: '99',
        name: '标记完成'
      }
    ]
  },
  onTouchStart: function (e) {
    let _this = this
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = _this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#f1f1f1'; // 设置为灰色
    _this.setData({
      dataList: dataList // 更新数据
    });
  },

  onTouchEnd: function (e) {
    let _this = this
    const index = e.currentTarget.dataset.index; // 获取当前项目的索引
    const dataList = _this.data.dataList.slice(); // 复制当前数组
    dataList[index].bgColor = '#ffffff'; // 恢复为白色
    _this.setData({
      dataList: dataList // 更新数据
    });
  },
  // 切换顶部导航
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  // 搜索输入事件（可结合接口做实时搜索，这里简单示例）
  onSearchInput(e) {
    let _this = this
    const value = e.detail.value;
    _this.setData({
      keyword: value
    })
  },

  // 显示筛选面板
  showFilter() {
    this.setData({
      showFilterPanel: !this.data.showFilterPanel
    });
  },

  // 选择快递状态
  chooseStatus(e) {
    let statusLast = this.data.status
    let status = e.currentTarget.dataset.status;
    status = status == statusLast ? '' : status
    this.setData({
      status: status
    });
  },

  // 选择分拣口
  choosePort(e) {
    let selectedIndex = this.data.selectedIndex
    let port = e.currentTarget.dataset.value;
    let index = e.currentTarget.dataset.index;
    index = selectedIndex === index ? '' : index
    port = index === '' ? '' : port
    this.setData({
      selectedIndex: index,
      port: port
    });
  },

  hideFilter() {
    this.setData({
      status: '',
      port: '',
      showFilterPanel: false
    });
  },

  // 重置筛选条件
  resetFilter() {
    let _this = this
    _this.setData({
      pageNo: 1,
      dataList: [],
      isLast: false,
      nodata: false,
      port: '',
      status: '',
      selectedIndex: ''
    });
  },

  // 确定筛选（可根据筛选条件调用接口查询快递列表）
  confirmFilter() {
    const {
      status,
      port,
      keyword
    } = this.data;
    console.log('筛选条件：', {
      status,
      port,
      keyword
    });
    this.setData({
      showFilterPanel: false,
      dataList: [],
      pageNo: 1
    });
    // 条件查询
    this.pageDeliveryNote()
  },

  // 前往客服（可跳转客服页面或唤起客服功能）
  goToService() {
    // 示例：跳转客服页面，需提前配置页面路由
    wx.navigateTo({
      url: '/pages/service/service'
    });
  },

  onShow() {
    if (app.globalData.userInfo.authStatus != 1) {
      return
    }
    this.resetFilter()
    this.pageDeliveryNote()
  },

  onLoad() {
    this.listWithPendingCount()
  },

  // 点击进入送货单详情页面
  bindDetail: function (e) {
    let params = e.currentTarget.dataset.model
    let newNoteDescription = params['newNoteDescription']
    params['noteDescription'] = ''
    params['newNoteDescription'] = ''
    wx.navigateTo({
      url: '/pages/MessageDetail/MessageDetail?value=' + JSON.stringify(params) + '&newNoteDescription=' + newNoteDescription
    })
  },

  // 点击进入分拣信息页面
  bindFDetail: function (e) {
    let params = e.currentTarget.dataset.model
    console.log('分拣信息', params)
    wx.navigateTo({
      url: '/pages/FMessageDetail/FMessageDetail?value=' + JSON.stringify(params)
    })
  },

  bindClear(e) {
    let _this = this
    _this.setData({
      keyword: '',
      pageNo: 1,
      dataList: [],
    })
    _this.pageDeliveryNote()
  },

  delete(e) {
    this.onTouchEnd(e)
    const index = e.currentTarget.dataset.index
    const id = e.currentTarget.dataset.model.id
    wx.showModal({
      title: '温馨提示',
      content: '是否删除',
      complete: (res) => {
        if (res.cancel) {

        }
        if (res.confirm) {
          this.deleteDeliveryNote(index, id)
        }
      }
    })
  },

  bindSearch() {
    let _this = this
    _this.data.dataList = []
    _this.data.pageNo = 1
    _this.data.nodata = false
    _this.data.isLast = false
    _this.pageDeliveryNote()
  },

  // 送货单查询
  pageDeliveryNote() {
    let _this = this;
    const {
      pageNo,
      pageSize,
      keyword,
      status,
      port
    } = _this.data
    var prams = {
      keyword: keyword,
      pageNo: pageNo,
      pageSize: pageSize,
      entCustomerId: app.globalData.userInfo.entId,
      sortingStatus: status,
      sortingPortNumber: port
    }
    var api = apis.pageDeliveryNote;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let total = res.data.total
        let list = res.data.list
        if (total == 0) {
          let nodata = _this.data.pageNo === 1 ? true : false
          _this.setData({
            isLast: true,
            nodata: nodata
          })
        } else {
          // 把描述字段格式化，展示一部分出来
          list.forEach(item => {
            item['newNoteDescription'] = utils.processString(item['noteDescription'])
            item['timestampDate'] = utils.timestampToDate(item['createTime'])
          });
          let isLast = (total < 10 && _this.data.pageNo === 1) ? true : false
          let allData = _this.data.dataList.concat(list)
          _this.setData({
            nodata: false,
            dataList: allData,
            isLast: isLast
          })
        }
      },
      function (err) {
        utils.showToast(err)
      })
  },

  deleteDeliveryNote(index, id) {
    let _this = this;
    let {
      dataList
    } = _this.data
    let api = apis.deleteDeliveryNote + '?id=' + id
    server.deleteRequest(config.xburl, api, {},
      function (res) {
        dataList.splice(index, 1)
        _this.setData({
          dataList: dataList
        })
        utils.showToast('删除成功')
      },
      function (err) {
        utils.showToast(err)
      })
  },

  markCompleted(e) {
    let _this = this;
    let {
      dataList,
      status
    } = _this.data
    const id = e.currentTarget.dataset.model.id
    const index = e.currentTarget.dataset.index
    if (status == '1') {
      utils.showToast('已完成分拣')
      return
    }
    if (status == '99') {
      utils.showToast('已标记完成')
      return
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '是否标记完成',
        complete: (res) => {
          if (res.confirm) {
            let api = apis.markCompleted + '?id=' + id
            server.putRequest(config.xburl, api, {},
              function (res) {
                utils.showToast('成功标记')
                dataList.splice(index, 1)
                _this.setData({
                  dataList: dataList
                })
              },
              function (err) {
                utils.showToast(err)
              })
          }
        }
      })
    }
  },


  //分页加载
  scrollToLower: function () {
    const {
      isLast,
      pageNo,
    } = this.data
    if (isLast) {
      utils.showToast('已经到底啦！')
    } else {
      this.setData({
        pageNo: parseInt(pageNo) + 1
      })
      this.pageDeliveryNote()
    }
  },

  onInput(e) {
    let _this = this
    let value = e.detail.value
    _this.setData({
      keyword: value
    })
  },

  listWithPendingCount() {
    let _this = this;
    var prams = {}
    let api = apis.listWithPendingCount;
    server.getRequest(config.xburl, api, prams,
      function (res) {
        let data = res.data
        _this.setData({
          options: data
        })
      },
      function (err) {
        utils.showToast(err)
      })
  },

});